/**
 * 
 */
package com.base.common.job;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.EmchatBodyMapper;
import com.base.common.persistent.dao.EmchatEntityMapper;
import com.base.common.persistent.dao.EmchatExtMapper;
import com.base.common.persistent.dao.EmchatPayloadMapper;
import com.base.common.persistent.dao.EmchatSizeMapper;
import com.base.common.utils.EasyUtil;
import com.base.common.utils.IDGenerator;
import com.ygj.easemob.server.example.api.ChatMessageAPI;
import com.ygj.easemob.server.example.api.HttpUtil;
import com.ygj.easemob.server.example.comm.ClientContext;
import com.ygj.easemob.server.example.comm.EasemobRestAPIFactory;
import com.ygj.easemob.server.example.comm.entity.Body;
import com.ygj.easemob.server.example.comm.entity.Entity;
import com.ygj.easemob.server.example.comm.entity.Ext;
import com.ygj.easemob.server.example.comm.entity.Payload;
import com.ygj.easemob.server.example.comm.entity.Size;

/**
 * 环信聊天记录导入
 * 
 * @author K
 *
 */
@Component("importEaseMobChatMessage")
public class ImportEaseMobChatMessage {
	Logger logger = Logger.getLogger(ImportEaseMobChatMessage.class);
	EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES).getAPIFactory();

	@Resource
	private EmchatBodyMapper emchatBodyMapper;
	@Resource
	private EmchatEntityMapper emchatEntityMapper;
	@Resource
	private EmchatExtMapper emchatExtMapper;
	@Resource
	private EmchatPayloadMapper emchatPayloadMapper;
	@Resource
	private EmchatSizeMapper emchatSizeMapper;
	
	@Resource
	private EasyUtil easyUtil;
	
	@Transactional
	@Scheduled(initialDelay=0, fixedRate=10000)
	public void importEaseMobChatMessage() {
		try {
			String ql = "select * where timestamp>1403164734226";
			Entity e = emchatEntityMapper.queryLastedEntity();
			if(e != null){
				ql = "select * where timestamp>" + String.valueOf(e.getTimestamp()).trim();
			}
			System.out.println(ql);
			
			ChatMessageAPI chatMessage = (ChatMessageAPI) factory.newInstance(EasemobRestAPIFactory.MESSAGE_CLASS);
//			System.out.println(chatMessage.exportChatMessages(null, null, "select * where timestamp>1475893754758"));
			List<Map> list = (List<Map>)(JsonUtil.string2Obejct(chatMessage.exportChatMessages(null, null, ql).toString().split("Response Body: ")[1].trim(), Map.class).get("entities"));
//			System.out.println(this.getClass().getClassLoader().getResource("/"));
			if(list != null){
				for(Map map : list){
					Entity entity = new Entity();
					entity.setUuid(String.valueOf(map.get("uuid")));
					entity.setCreated(Long.valueOf(map.get("created").toString()));
					entity.setFrom(String.valueOf(map.get("from")));
					entity.setTo(String.valueOf(map.get("to")));
					entity.setTimestamp(Long.valueOf(map.get("timestamp").toString()));
					entity.setModified(Long.valueOf(map.get("modified").toString()));
					entity.setMsg_id(String.valueOf(map.get("msg_id")));
					entity.setType(String.valueOf(map.get("type")));
					entity.setChat_type(String.valueOf(map.get("chat_type")));
					if("groupchat".equals(String.valueOf(map.get("chat_type")))){
						entity.setGroupId(String.valueOf(map.get("groupId")));
					}
					
					Payload payload = new Payload();
					payload.setUuid(IDGenerator.getUUID());
					
					Map payloadMap = ((Map)map.get("payload"));
					Map extMap = (Map) payloadMap.get("ext");
					
					Ext ext = new Ext();
					ext.setUuid(IDGenerator.getUUID());
					ext.setChatUserNick(extMap.get("ChatUserNick") == null ? null : extMap.get("ChatUserNick").toString());
					ext.setChatUserPic(extMap.get("ChatUserPic") == null ? null : extMap.get("ChatUserPic").toString());
					emchatExtMapper.addEmchatExt(ext);
					
					payload.setExt(emchatExtMapper.queryByUuid(ext.getUuid()));
					emchatPayloadMapper.addEmchatPayload(payload);
					
					payload = emchatPayloadMapper.queryByUuid(payload.getUuid());
					
					entity.setPayload(payload);
					emchatEntityMapper.addEmchatEntity(entity);
					
					List<Map> bodiesMap = (List<Map>) payloadMap.get("bodies");
					for(Map bodyMap : bodiesMap){
						String type = bodyMap.get("type").toString();

						Body body = new Body();
						body.setType(type);
						body.setUuid(IDGenerator.getUUID());
						
						switch (type) {
						case "txt":
							body.setMsg(bodyMap.get("msg").toString());
							break;
							
						case "img":
							body.setFilename(bodyMap.get("filename").toString());
							body.setFile_length(Integer.valueOf(bodyMap.get("file_length").toString()));
							body.setSecret(bodyMap.get("secret").toString());
							body.setThumbFilename(bodyMap.get("thumbFilename").toString());
							body.setUrl(downloadFile(bodyMap.get("url").toString(), "D:", "/emchat", ""));
							
							Size size = new Size();
							Map sizeMap = (Map) bodyMap.get("size");
							size.setUuid(IDGenerator.getUUID());
							size.setHeight(Double.valueOf(sizeMap.get("height").toString()));
							size.setWidth(Double.valueOf(sizeMap.get("width").toString()));
							emchatSizeMapper.addEmchatSize(size);
							
							body.setSize(emchatSizeMapper.queryByUuid(size.getUuid()));
							break;
							
						case "audio":
							body.setFilename(bodyMap.get("filename").toString());
							body.setFile_length(Integer.valueOf(bodyMap.get("file_length").toString()));
							body.setLength(Integer.valueOf(bodyMap.get("length").toString()));
							body.setSecret(bodyMap.get("secret").toString());
							body.setUrl(downloadFile(bodyMap.get("url").toString(), "D:", "/emchat", ""));
							break;

						default:
							break;
						}
						
						body.setPayload(payload);
						
						emchatBodyMapper.addEmchatBody(body);
						
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	public String downloadFile(String fileUrl, String basePath,
			String sysImagesFile, String picUrls) throws IOException {
		String[] fileUrls = fileUrl.split(";");
		String realPath = "D:\\" + sysImagesFile;
		File f = new File(realPath);
		if (!f.exists()) {
			f.mkdir();
		}
		for (int i = 0; i < fileUrls.length; i++) {
			String[] fileNames = fileUrls[i].split("/"); // 获取文件名

			
			final String saveUrl = (realPath + "\\" + fileNames[fileNames.length - 1]).replaceAll("\\\\", "/");
			if ("".equals(picUrls.trim())) {
				picUrls += basePath + sysImagesFile + "/"
						+ fileNames[fileNames.length - 1];
			} else {
				picUrls += ";" + basePath + sysImagesFile + "/"
						+ fileNames[fileNames.length - 1];
			}

			final String downUrl = fileUrls[i];
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					try {
						HttpUtil httpUtil = new HttpUtil();
						DataInputStream dataInputStream = null;
						DataOutputStream dataOutputStream = null;
						dataInputStream = new DataInputStream((InputStream)HttpUtil.doGet(downUrl));
						dataOutputStream = new DataOutputStream(new FileOutputStream(saveUrl));
						IOUtils.copy(dataInputStream, dataOutputStream);
						dataOutputStream.flush();
						if (dataInputStream != null) {
							dataInputStream.close();
						}
						if (dataOutputStream != null) {
							dataOutputStream.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					
				}
			}).start();
			
			
		}
		return picUrls;
	}
}
